from PyQt5.QtCore import QObject, pyqtSignal, QByteArray, QDataStream, QIODevice
from PyQt5.QtNetwork import QUdpSocket, QHostAddress
import json
import struct
from logger import logger
from context import Component

@Component('sensor')
class Sensor(QObject):
    # 定义信号用于数据更新
    data_received = pyqtSignal(int, object)
    
    def __init__(self):
        super().__init__()
        self.socket = None
        self.port = 12345  # 默认UDP端口
        self.running = False
        self.start()
    
    def start(self, port=None):
        """启动UDP服务器"""
        if port is not None:
            self.port = port
            
        if self.socket:
            self.socket.close()
            
        self.socket = QUdpSocket()
        
        # 绑定端口
        if not self.socket.bind(QHostAddress.Any, self.port):
            logger.error(f"无法绑定UDP端口 {self.port}")
            return False
            
        # 连接readyRead信号到处理函数
        self.socket.readyRead.connect(self.process_pending_datagrams)
        self.running = True
        logger.info(f"UDP服务器已启动，监听端口：{self.port}")
        return True
    
    def stop(self):
        """停止UDP服务器"""
        if self.socket:
            self.socket.close()
            self.socket = None
        self.running = False
        logger.info("UDP服务器已停止")
    
    def process_pending_datagrams(self):
        """处理所有等待的数据包"""
        while self.socket and self.socket.hasPendingDatagrams():
            # 获取待接收数据大小
            size = self.socket.pendingDatagramSize()
            
            data, sender, port = self.socket.readDatagram(size)
            
            try:
                # 解析数据
                self.parse_data(data)
                logger.debug(f"收到来自 {sender.toString()}:{port} 的数据")
            except Exception as e:
                logger.error(f"解析数据包时出错: {str(e)}")
    
    def parse_data(self, datagram):
        """解析接收到的数据
        
        数据格式预期为JSON，格式如：
        {"id": 1, "value": 10.5}
        或二进制，格式为：
        [4字节整数id][4字节浮点数值]
        """
        try:
            # 尝试作为JSON解析
            data_str = datagram.decode('utf-8')
            # logger.debug(f"接收到的数据: {data_str}")
            
            data = json.loads(data_str)
            sensor_id = int(data.get('id'))
            value = data.get('value')
            
            if sensor_id is not None and value is not None:
                # 发出信号，传递传感器ID和值
                self.data_received.emit(sensor_id, value)
                # logger.debug(f"解析JSON数据: ID={sensor_id}, 值={value}")
                return
        except (json.JSONDecodeError, UnicodeDecodeError, AttributeError) as e:
            logger.error(f"JSON解析错误: {str(e)}")